package graph.day15;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Leetcode_113 {

    List<List<Integer>> res = new LinkedList<>();
    List<Integer> path = new ArrayList<>();

    // dfs
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) return res;
        dfs(0, root, targetSum);
        return res;
    }

    public void dfs(int sum, TreeNode root, int targetSum) {
        if (root.left == null && root.right == null) {
            int currentSum = sum + root.val;
            if (currentSum == targetSum) {
                path.add(root.val);
                res.add(new LinkedList<>(path));
                path.remove(path.size() - 1);
            }
            return;
        }
        int currentSum = sum + root.val;
        path.add(root.val);
        if (root.left != null) dfs(currentSum, root.left, targetSum);
        if (root.right != null) dfs(currentSum, root.right, targetSum);
        path.remove(path.size() - 1);
    }
}
